#include "GameWindow4.h"
#include "./ui_widget.h"
#include <QGraphicsSceneMouseEvent>
#include <QDebug>
#include <qaudiooutput.h>

GameWindow4::GameWindow4(QWidget *parent)
    : QGraphicsView(parent),
    scene(new QGraphicsScene(this)),
    currentLight(nullptr),
    currentIndex(0)

{
    setScene(scene);
    setFixedSize(800,600);
    scene->setSceneRect(0, 0, 800, 600);

    initScene();
    initLightData();
    loadNextLight();
}

void GameWindow4::initScene()
{
    // 加载背景
    QPixmap bg("D:/QtCreator/HeartIslandTest/figures/puppybackground.jpg");
    background=scene->addPixmap(bg.scaled(800, 600));
    background->setZValue(-1);


    // 小狗图加载
    dogLeftPixmap = QPixmap("D:/QtCreator/HeartIslandTest/figures/puppyrunningleft.png");
    dogRightPixmap = QPixmap("D:/QtCreator/HeartIslandTest/figures/puppyrunningright.png");

    dog = scene->addPixmap(dogLeftPixmap);
    dog->setPos(-10, 20);
    dog->setZValue(10);
    qDebug() << "小狗加载成功，位置是：" << dog->pos();
    qDebug() << "狗狗是否可见：" << dog->isVisible();

    // 左箭头按钮
    QPixmap leftArrowPixmap("D:/QtCreator/HeartIslandTest/figures/arrowleft.jpg");
    leftArrow = scene->addPixmap(leftArrowPixmap.scaled(50, 50));
    leftArrow->setPos(30, 520);
    leftArrow->setZValue(1);
    leftArrow->setData(0, "left");

    // 右箭头按钮
    QPixmap rightArrowPixmap("D:/QtCreator/HeartIslandTest/figures/arrowright.jpg");
    rightArrow = scene->addPixmap(rightArrowPixmap.scaled(50, 50));
    rightArrow->setPos(720, 520);
    rightArrow->setZValue(1);
    rightArrow->setData(0, "right");

    // 启用鼠标事件拦截
    leftArrow->setAcceptedMouseButtons(Qt::LeftButton);
    rightArrow->setAcceptedMouseButtons(Qt::LeftButton);
}


 void GameWindow4::initLightData()
{
    allLightOptions = {
        { "D:/QtCreator/HeartIslandTest/figures/bubble.jpg", "可以先深呼吸一下再慢慢处理吗？" ,"breathGuide"},
        { "D:/QtCreator/HeartIslandTest/figures/bubble.jpg", "要听音乐吗？","playMusic" },
        { "D:/QtCreator/HeartIslandTest/figures/bubble.jpg", "要抱抱吗？", "showHug"}
    };

    std::shuffle(allLightOptions.begin(), allLightOptions.end(), *QRandomGenerator::global());

    int total = QRandomGenerator::global()->bounded(6);
    selectedLights = allLightOptions.mid(0, total);
    currentIndex=0;
}

void GameWindow4::onLightClicked(int index)
{
    LightOption current = selectedLights[index];
    showMessageDialog(current.message, current.actionType);
}

void GameWindow4 ::loadNextLight()
{
    if (currentIndex >= selectedLights.size()) return;

    LightOption data = selectedLights[currentIndex];

    QPixmap pix(data.imagePath);
    currentLight = new QGraphicsPixmapItem(pix);
    currentLight->setTransformOriginPoint(pix.width() / 2, pix.height() / 2); // 关键：设置原点为中心
    currentLight->setScale(0.05);

    int randomX = QRandomGenerator::global()->bounded(-200, 400) + dog->x();  // 出现在小狗前面
    currentLight->setPos(randomX,30);
    currentLight->setZValue(0);
    scene->addItem(currentLight);
}

void GameWindow4::keyPressEvent(QKeyEvent *event)
{
    if (event->key() == Qt::Key_Left) {
        moveDogLeft();
    } else if (event->key() == Qt::Key_Right) {
        moveDogRight();
    }
    checkProximity();
}
void GameWindow4::checkProximity()
{
    if (!currentLight) return;

    qreal dogX = dog->x();
    qreal lightX = currentLight->x();

    if (qAbs(dogX - lightX) < 10) {
        // 调用带 actionType 的弹窗逻辑
        const LightOption &light = selectedLights[currentIndex];
        showMessageDialog(light.message, light.actionType);

        scene->removeItem(currentLight);
        delete currentLight;
        currentLight = nullptr;

        currentIndex++;
        loadNextLight();
    }
}
void GameWindow4::playSound(const QString &filePath)
{
    QMediaPlayer *player = new QMediaPlayer(this);
    QAudioOutput *audioOutPut = new QAudioOutput(this);
    player->setAudioOutput(audioOutPut);
    audioOutPut->setVolume(0.5);
    player->setSource(QUrl::fromLocalFile(filePath));  // 设置文件路径
    player->play();  // 播放音频
}

void GameWindow4::showMessageDialog(const QString &message,const QString &actionType)
{
    CustomMessageDialog *dialog = new CustomMessageDialog(message, this);
    dialog->setWindowTitle("遇见了...");
    dialog->setFixedSize(500, 150);
    dialog->show();
    QTimer::singleShot(2000, dialog, [=]() {
        if (dialog->isVisible()) {
            emit dialog->dialogResult(false);  // 模拟点击「不要」
            dialog->close();
        }
    });

    connect(dialog, &CustomMessageDialog::dialogResult, this, [=](bool accepted) {
        if (accepted) {
            if (actionType == "playMusic") {
               ui=new Ui::Widget;
                player=new QMediaPlayer(this);
               audioOutPut=new QAudioOutput(this);
                ui->setupUi(this);
                playSound("C:/Users/Annie Tang/Music/Sufjan Stevens - Eugene.ogg");
            } else if (actionType == "showHug") {
                QLabel *gifLabel = new QLabel(this);
                QMovie *movie = new QMovie("D:/QtCreator/HeartIslandTest/figures/hug.gif");
                gifLabel->setMovie(movie);
                gifLabel->setGeometry(200, 200, 300, 300);
                movie->setScaledSize(QSize(300, 300));
                gifLabel->show();
                movie->start();
                QTimer::singleShot(3000, gifLabel, [gifLabel]() {
                    gifLabel->close();
                    gifLabel->deleteLater();
                });
            } else if (actionType == "breathGuide") {
                QLabel *breathLabel = new QLabel(this);
                QMovie *movie= new QMovie("D:/QtCreator/HeartIslandTest/figures/Peace Breathe Sticker by Jon Burgerman.gif");
                breathLabel->setMovie(movie);
                breathLabel->setGeometry(200, 200, 300, 300);
                movie->setScaledSize(QSize(300, 500));
                breathLabel->show();
                movie->start();
                QTimer::singleShot(12000, breathLabel, [breathLabel]() {
                    breathLabel->close();
                    breathLabel->deleteLater();
                });
            }
        } else {
            qDebug() << "用户点击了「不要」";
        }

        scene->removeItem(currentLight);
        delete currentLight;
        currentLight = nullptr;

        currentIndex++;
        loadNextLight();
    });
}

// 点击箭头处理（重写 scene 的事件传递）
bool GameWindow4::viewportEvent(QEvent *event)
{
    if (event->type() == QEvent::MouseButtonPress) {
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);
        QPointF scenePos = mapToScene(mouseEvent->pos());

        QGraphicsItem *clickedItem = scene->itemAt(scenePos, QTransform());
        if (clickedItem && clickedItem->data(0).isValid()) {
            QString direction = clickedItem->data(0).toString();
            if (direction == "left") {
                moveDogLeft();
            } else if (direction == "right") {
                moveDogRight();
            }
        }
    }
    return QGraphicsView::viewportEvent(event);
}

void GameWindow4::moveDogLeft()
{
    dog->moveBy(-moveStep, 0);
    dog->setPixmap(dogLeftPixmap);
}

void GameWindow4::moveDogRight()
{
    dog->moveBy(moveStep, 0);
    dog->setPixmap(dogRightPixmap);
}
void GameWindow4::closeEvent(QCloseEvent *event) {
    emit gameWindow4Closed();
    QWidget::closeEvent(event);
}

CustomMessageDialog::CustomMessageDialog(const QString &message, QWidget *parent)
    : QDialog(parent)
{
    // 设置窗口样式
    setWindowTitle("遇见回忆");
    setFixedSize(400, 250);
    setStyleSheet(
            "QDialog {"
            "   background-image: url('D:/QtCreator/HeartIslandTest/figures/dialog_bg.png');"
            "   background-position: center;"
            "   border-radius: 15px;"
        "}"
        "QLabel {"
        "   font-size: 18px;"
        "   color: #8B4513;"
        "   font-weight: bold;"
        "}"
        "QPushButton {"
        "   background: #8B4513;"
        "   color: white;"
        "   border: none;"
        "   padding: 8px 16px;"
        "   border-radius: 10px;"
        "   font-size: 16px;"
        "}"
        "QPushButton:hover {"
        "   background: #A0522D;"
        "}"
        );

    // 消息文本
    QLabel *label = new QLabel(message, this);
    label->setAlignment(Qt::AlignCenter);

    // 按钮
    btnAccept = new QPushButton("好", this);
    btnReject = new QPushButton("不要", this);

    // 布局
    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(label, 1, Qt::AlignCenter);

    QHBoxLayout *btnLayout = new QHBoxLayout();
    btnLayout->addStretch();
    btnLayout->addWidget(btnAccept);
    btnLayout->addWidget(btnReject);
    btnLayout->addStretch();

    layout->addLayout(btnLayout);

    // 连接按钮信号
    connect(btnAccept, &QPushButton::clicked, this, [=]() {
        emit dialogResult(true);
        this->close();
    });
    connect(btnReject, &QPushButton::clicked, this, [=]() {
        emit dialogResult(false);
        this->close();
    });

}
